<template>
	<div class="pushaddress">
		<van-nav-bar class="custom-nav-bar" title="更新地址" left-text="返回" left-arrow @click-left="onClickLeft" />
		<div>
			<van-cell-group inset>
				<van-field v-model="username" required label="用户名" placeholder="请输入用户名" />
				<van-field v-model="phone" required label="手机号" placeholder="请输入手机号"
					:error-message="isPhoneInvalid ? '手机号格式错误' : ''" />
			</van-cell-group>
			
			<van-cell-group inset>
				<van-field v-model.trim="address" required label="详细地址" placeholder="请输入详细地址" />
				<van-field name="switch" label="默认地址" class="address-cl">
					<template #input>
						<van-switch v-model="checked" 
					
						class="switch-right" />
					</template>
				</van-field>
			</van-cell-group>
		</div>
		<div class="push" @click="updata">
			更新地址
		</div>
	</div>
</template>

<style lang="less" scoped></style>

<script setup lang="ts">
import { ref, computed, watch,onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { areaList } from '@vant/area-data';
import { Token } from '@/utils/request';
import { showToast } from 'vant';
const $router = useRouter();
const onClickLeft = () => $router.back();

const username:any = ref('');
const phone:any = ref('');
const result:any = ref('');
const address:any = ref('');
const moren:any = ref();
const showPicker = ref(false);
const checked = ref(false);
const address_id:any = ref('');



//新建地址接口
const updata = () => {
	Token('/api/address', 'put', {
		phone: phone.value,
		name: username.value,
		address: address.value,
		moren: moren.value,
        address_id:address_id.value
	}).then((res: any) => {
		if (res.status == 200) {
			showToast('修改地址成功');
			$router.push('/address');
		}
	});
};

// 定义 onConfirm 方法
const onConfirm = (e: any) => {
	result.value = e.selectedOptions[0].text + ' ' + e.selectedOptions[1].text + ' ' + e.selectedOptions[2].text;
	showPicker.value = false;
};

// 手机号验证逻辑
const isPhoneInvalid = computed(() => {
	const phonePattern = /^1[3-9]\d{9}$/;
	return !phonePattern.test(phone.value) && phone.value !== '';
});

//初始化赋值

onMounted(() => {
    username.value=$router.currentRoute.value.query.name,
    phone.value=$router.currentRoute.value.query.phone,
    address.value=$router.currentRoute.value.query.address,
    moren.value=$router.currentRoute.value.query.moren,
    address_id.value=$router.currentRoute.value.query.address_id
   if( moren.value == '1'){
    checked.value = true
   }
   
}
)

//监听moren
watch(checked, (newValue, oldValue) => {
    if (checked.value == false) {
        moren.value = '0';
    } else {
        moren.value = '1';
    }
});
</script>
<style scoped>
.city {
	margin-left: 34px;
}

.address-cl {
	margin-left: 17px;
}

.push {
	width: 100%;
	margin: 0 auto;
	position: fixed;
	bottom: 0;
	height: 100px;
	background-color: rgb(63, 161, 157);
	text-align: center;
	line-height: 100px;
	font-size: 30px;
	color: #fff;
}

.switch-right {
	position: absolute;
	right: 50px;	
}
</style>